package com.ws.shop.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.ws.shop.util.BOSSecurity;
import com.ws.shop.util.Tools;

public class ConnectManager {

	/** 数据源，static */
	private static String username;
	private static String password;
	private static String driver;

	private static Logger log = Logger.getLogger(ConnectManager.class);

	private static StringBuffer connecturl = new StringBuffer(); // 数据库连接url
	static {
		connecturl.append("jdbc:mysql://");
		connecturl.append(Messages.getString("db.host").trim());
		connecturl.append(":3306/");
		connecturl.append(Messages.getString("db.name").trim());
		connecturl.append("?useUnicode=true&characterEncoding=UTF-8");
		driver = Messages.getString("db.driver").trim();
		try {
			System.out.println("" + Messages.getString("db.maxWait").trim());
			username = BOSSecurity.decode64(Messages.getString("db.user").trim());
			String pwd = Messages.getString("db.pwd");
			if (pwd == null || pwd.trim().equals("")) {
				pwd = "";
			} else {
				pwd = BOSSecurity.decode64(pwd.trim());
			}
			password = pwd;
			Class.forName(driver).newInstance();
		} catch (Exception e) {
			log.error("数据库密码错误：或者数据库连接配置信息有错误" + Tools.getStackTrace(e));
			e.printStackTrace();
		}
	}

	/**
	 * 更新
	 * 
	 * @return
	 * @throws Exception 
	 */
	public static Connection getConnection() throws Exception {
		try {
			Connection connection = DriverManager.getConnection(connecturl.toString(), username, password);
			return connection;
		} catch (SQLException e) {
			log.error("链接数据库出错！", e);
			throw new Exception("链接数据库出错");
		}
	}

	public static void close(Connection connect, Statement stmt, ResultSet rs) {
		try {
			if (connect != null) {
				connect.close();
			}

			if (stmt != null) {
				stmt.close();
			}

			if (rs != null) {
				rs.close();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
